<template>
  <a-drawer v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false"
    :width="width >= 500 ? 500 : '100%'" draggable @before-ok="save" @close="reset">
    <GiForm ref="formRef" v-model="form" :columns="columns"></GiForm>
  </a-drawer>
</template>

<script setup lang="ts">
  import { Message } from '@arco-design/web-vue'
  import { useWindowSize } from '@vueuse/core'
  import { getDeviceRecords, addDeviceRecords, updateDeviceRecords } from '@/apis/asset/device/records'
  import { type ColumnItem, GiForm } from '@/components/GiForm'
  import { useResetReactive } from '@/hooks'
  import { useDict } from '@/hooks/app'
  import { useDept } from '@/hooks/app'
  import { deviceCategory } from '@/hooks/asset'
  import { deviceBrand } from '@/hooks/asset'
  import { deviceModel } from '@/hooks/asset'
  import { producer } from '@/hooks/asset'
  import { depreacitionRules } from '@/hooks/asset'

  const emit = defineEmits < {
    (e: 'save-success'): void
  }> ()

  const { width } = useWindowSize()

  const dataId = ref('')
  const visible = ref(false)
  const isUpdate = computed(() => !!dataId.value)
  const title = computed(() => (isUpdate.value ? '修改设备' : '新增设备'))
  const formRef = ref < InstanceType < typeof GiForm >> ()
  const { deptList, getDeptList } = useDept()
  const { deviceCategoryList, getDeviceCategoryList } = deviceCategory()
  const { deviceBrandList, getDeviceBrandList } = deviceBrand()
  const { deviceModelList, getDeviceModelList } = deviceModel()
  const { producerList, getProducerList } = producer()
  const { depreacitionRulesList, getDepreacitionRules } = depreacitionRules()
  
  const [form, resetForm] = useResetReactive({
    // todo 待补充
  })

  // 递归查找节点
  const findNodeByValue = (tree, value) => {
    for (const node of tree) {
      if (node.key === value) {
        return node;
      }
      if (node.children) {
        const result = findNodeByValue(node.children, value);
        if (result) {
          return result;
        }
      }
    }
    return null;
  }

  const columns: ColumnItem[] = reactive([
    {
      label: '编号',
      field: 'code',
      type: 'input',
      span: 24,
      props: {
        maxLength: 50,
      },
      rules: [{ required: true, message: '请输入编号' }]
    },
    {
      label: '分类',
      field: 'categoryId',
      type: 'tree-select',
      span: 24,
      required: true,
      props: {
        data: deviceCategoryList,
        allowClear: true,
        allowSearch: true,
        fallbackOption: false,
        filterTreeNode(searchKey: string, nodeData: TreeNodeData) {
          if (nodeData.title) {
            return nodeData.title.toLowerCase().includes(searchKey.toLowerCase())
          }
          return false
        },
        onChange(value) {
          // 根据 value 查找对应的节点
          const selectedNode = findNodeByValue(deviceCategoryList.value, value);
          if (selectedNode) {
            form.name = selectedNode.title; // 更新表单数据
          }
        },

      },
    },
    {
      label: '品牌',
      field: 'brand',
      type: 'select',
      span: 24,
      required: true,
      props: {
        options: deviceBrandList,
        placeholder: "请选择或输入",
        allowClear: true,
        allowSearch: true,
        allowCreate: true,
        onChange(value) {
          form.name = form.name + "-" + value;
        },
      }
    },
    {
      label: '型号',
      field: 'model',
      type: 'select',
      span: 24,
      required: true,
      props: {
        options: deviceModelList,
        placeholder: "请选择或输入",
        allowClear: true,
        allowSearch: true,
        allowCreate: true,
        onChange(value) {
          form.name = form.name + "-" + value;
        },
      }
    },
    {
      label: '名称',
      field: 'name',
      type: 'input',
      span: 24,
      props: {
        maxLength: 50,
      },
      rules: [{ required: true, message: '请输入名称' }]
    },

    {
      label: '序列号',
      field: 'sn',
      type: 'input',
      span: 24,
      props: {
        maxLength: 50,
      },
    },
    {
      label: '折旧规则',
      field: 'depreciationRuleId',
      type: 'select',
      span: 24,
      props: {
        options: depreacitionRulesList,
        placeholder: "请选择",
        allowClear: true,
        allowSearch: true,
        allowCreate: true
      }
    },
    {
      label: '供应商',
      field: 'producerId',
      type: 'select',
      span: 24,
      props: {
        options: producerList,
        placeholder: "请选择",
        allowClear: true,
        allowSearch: true,
      }
    },
    {
      label: '采购单价',
      field: 'price',
      type: 'input-number',
      span: 24,
      props: {
        maxLength: 0,
      },
    },
    {
      label: '采购日期',
      field: 'purchaseDate',
      type: 'date-picker',
      span: 24,
    },
    {
      label: '过保日期',
      field: 'expireDate',
      type: 'date-picker',
      span: 24,
    },
    {
      label: '描述',
      field: 'description',
      type: 'textarea',
      span: 24,
      props: {
        maxLength: 250,
      },
    },
  ])

  // 重置
  const reset = () => {
    formRef.value?.formRef?.resetFields()
    resetForm()
  }

  // 保存
  const save = async () => {
    try {
      const isInvalid = await formRef.value?.formRef?.validate()
      if (isInvalid) return false
      if (isUpdate.value) {
        await updateDeviceRecords(form, dataId.value)
        Message.success('修改成功')
      } else {
        await addDeviceRecords(form)
        Message.success('新增成功')
      }
      emit('save-success')
      return true
    } catch (error) {
      return false
    }
  }

  // 新增
  const onAdd = async () => {
    reset()
    if (!deptList.value.length) {
      await getDeptList()
    }
    if (!deviceCategoryList.value.length) {
      await getDeviceCategoryList()
    }
    await getDeviceBrandList()
    await getDeviceModelList()
    await getProducerList()
    await getDepreacitionRules()
    dataId.value = ''
    visible.value = true
  }

  // 修改
  const onUpdate = async (id: string) => {
    reset()
    if (!deptList.value.length) {
      await getDeptList()
    }
    if (!deviceCategoryList.value.length) {
      await getDeviceCategoryList()
    }
    await getDeviceBrandList()
    await getDeviceModelList()
    await getProducerList()
    await getDepreacitionRules()

    dataId.value = id
    const { data } = await getDeviceRecords(id)
    Object.assign(form, data)
    visible.value = true
  }

  defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss"></style>